package com.ytktt.study.week12.task4.redis;

import com.ytktt.study.week12.task4.redis.constant.RedisConstant;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.types.Expiration;

import java.util.concurrent.TimeUnit;

/**
 * 参考: <a href="https://github.com/Jaskey/RocketMQDedupListener/blob/master/src/main/java/com/github/jaskey/rocketmq/persist/RedisPersist.java">RocketMQ的幂等示例</a>
 *
 * @author ytk
 */
@RequiredArgsConstructor
public class RedisOperator {

    private final RedisTemplate<String, Object> redisTemplate;

    public boolean lockConsumerState(String uniqueId) {
        String key = this.genOrderStateKey(uniqueId);
        Boolean execute = redisTemplate.execute((RedisCallback<Boolean>) redisConnection ->
                redisConnection.set(key.getBytes(), RedisConstant.CONSUMING.getBytes(),
                        Expiration.milliseconds(TimeUnit.MINUTES.toMillis(5L)),
                        RedisStringCommands.SetOption.SET_IF_ABSENT));
        if (execute == null) {
            return false;
        }

        return execute;
    }

    public void deleteConsumerState(String uniqueId) {
        String key = this.genOrderStateKey(uniqueId);
        this.redisTemplate.delete(key);
    }

    public void markConsumed(String uniqueId) {
        String key = this.genOrderStateKey(uniqueId);
        this.redisTemplate.opsForValue().set(key, RedisConstant.CONSUMED, 2, TimeUnit.DAYS);
    }

    public String get(String uniqueId) {
        String key = this.genOrderStateKey(uniqueId);
        return (String) this.redisTemplate.opsForValue().get(key);
    }

    private String genOrderStateKey(String uniqueId) {
        return String.format(RedisConstant.ORDER_CONSUMER_STATE_KEY, uniqueId);
    }

}
